package cn.iocoder.yudao.module.fengdong.smartelderly.service.buyrecord;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.dataobject.commodity.CommodityDO;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.mysql.commodity.CommodityMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import cn.iocoder.yudao.module.fengdong.smartelderly.controller.admin.buyrecord.vo.*;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.dataobject.buyrecord.BuyRecordDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.fengdong.smartelderly.convert.buyrecord.BuyRecordConvert;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.mysql.buyrecord.BuyRecordMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.fengdong.smartelderly.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 购买记录 Service 实现类
 *
 * @author 沣东养老院管理员
 */
@Service
@Validated
public class BuyRecordServiceImpl implements BuyRecordService {

    @Resource
    private BuyRecordMapper buyRecordMapper;

    @Resource
    private CommodityMapper commodityMapper;

    private final Lock lock = new ReentrantLock(); // 创建一个锁对象


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createBuyRecord(BuyRecordCreateReqVO createReqVO) {

        CommodityDO commodityDO = commodityMapper.selectById(createReqVO.getCommodityId());
        if (ObjectUtil.isEmpty(commodityDO)) {
            throw exception(COMMODITY_NOT_EXISTS);
        }
        lock.lock();
        try {
            Long stock = commodityDO.getInventory();
            Long sellNum = commodityDO.getSellNum();
            if (stock!=null && stock > 0) {
                // 插入
                commodityDO.setInventory(stock-1);
                commodityDO.setSellNum(sellNum+1);
                commodityMapper.updateById(commodityDO);

                BuyRecordDO buyRecord = BuyRecordConvert.INSTANCE.convert(createReqVO);
                if (commodityDO.getType()==2||commodityDO.getType()==3 &&commodityDO.getDuration()!=null) {
                    buyRecord.setCreateTime(LocalDateTime.now());
                    buyRecord.setCreateTime(LocalDateTime.now().plusDays(commodityDO.getDuration()));
                }
                buyRecordMapper.insert(buyRecord);
                // 返回
                return buyRecord.getId();
            } else {
                throw exception(COMMODITY_COUNT_NOT_EXISTS);
            }
        } finally {
            lock.unlock(); // 释放锁
        }
    }

    @Override
    public void updateBuyRecord(BuyRecordUpdateReqVO updateReqVO) {
        // 校验存在
        validateBuyRecordExists(updateReqVO.getId());
        // 更新
        BuyRecordDO updateObj = BuyRecordConvert.INSTANCE.convert(updateReqVO);
        buyRecordMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBuyRecord(Long id) {
        BuyRecordDO buyRecordDO = buyRecordMapper.selectById(id);
        // 删除
        buyRecordMapper.deleteById(id);
        if (buyRecordDO == null) {
            throw exception(BUY_RECORD_NOT_EXISTS);
        }
        CommodityDO commodityDO = commodityMapper.selectById(buyRecordDO.getCommodityId());
        commodityDO.setInventory(commodityDO.getInventory()+1);
        commodityDO.setSellNum(commodityDO.getSellNum()+1);
        commodityMapper.updateById(commodityDO);
    }

    private void validateBuyRecordExists(Long id) {
        if (buyRecordMapper.selectById(id) == null) {
            throw exception(BUY_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public BuyRecordDO getBuyRecord(Long id) {
        return buyRecordMapper.selectById(id);
    }

    @Override
    public List<BuyRecordDO> getBuyRecordList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return buyRecordMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<BuyRecordDO> getBuyRecordPage(BuyRecordPageReqVO pageReqVO) {
        return buyRecordMapper.selectPage(pageReqVO);
    }

    @Override
    public List<BuyRecordDO> getBuyRecordList(BuyRecordExportReqVO exportReqVO) {
        return buyRecordMapper.selectList(exportReqVO);
    }

}
